<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/3/23
 * Time: 17:25
 */
namespace app\admin\controller;
use think\Db;
class InformationController extends CommonController
{
    /**
     *getInfoData 获取资讯数据
     * @return json格式数组
     */
    public function getInfoData(){
        $where =array();
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        if(isset($_POST['keyword']) && $_POST['keyword']!=''){
            $keyword = $_POST['keyword'];
            $where['el.life_title|el.life_content'] = array('like',"%$keyword%");
        }
        if(isset($_POST['lifetype']) && $_POST['lifetype']!=''){
            $lifetype = $_POST['lifetype'];
            $where['life_type'] = array('like',"%$lifetype%");
        }
        $where['life_new_type'] = 4;
        $res = Db::table('ew_life')
            ->alias ('el')
            ->join('ew_life_type elt','el.life_type=elt.lt_id','LEFT')
            ->where($where)
            ->field('life_id,life_number,life_zan,life_message,life_title,life_image,life_type,life_time,lt_name')
            ->order('life_time DESC')
            ->limit($rows * ($page - 1), $rows)
            ->select();
        $total =Db::table('ew_life')
            ->alias ('el')
            ->join('ew_life_type elt','el.life_type=elt.lt_id')
            ->where($where)
            ->count();
        $data['total'] = $total;
        $data['rows'] = $res;
        return json_encode($data);
    }
    public function getThreeInfoData(){
        $where =array();
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        if(isset($_POST['keyword']) && $_POST['keyword']!=''){
            $keyword = $_POST['keyword'];
            $where['el.life_title|el.life_content'] = array('like',"%$keyword%");
        }
        if(isset($_POST['user_username']) && $_POST['user_username']!=''){
            $keyword2 = $_POST['user_username'];
            $where['u.user_username'] = array('like',"%$keyword2%");
        }
        if(isset($_POST['life_new_type']) && $_POST['life_new_type']!=''){
            $lifetype = $_POST['life_new_type'];
            $where['life_new_type'] = $lifetype;
        }else{
            $where['life_new_type'] = array('in','1,2,3');
        }
        $field = "life_id,life_zan,life_message,life_title,life_image,life_time,life_number";
        $field .= ",life_new_type,u.user_id,u.user_username,life_shi,a.district";
        $res = Db::table('ew_life')->alias ('el')
            ->join('ew_u_user u','el.life_user_id=u.user_id','LEFT')
            ->join('ew_area a','el.life_shi=a.district_id','LEFT')
            ->where($where)
            ->field($field)
            ->order('life_time DESC')
            ->limit($rows * ($page - 1), $rows)
            ->select();
        $total =Db::table('ew_life')->alias ('el')
            ->join('ew_u_user u','el.life_user_id=u.user_id','LEFT')
            ->join('ew_area a','el.life_shi=a.district_id','LEFT')
            ->where($where)
            ->count();
        $data['total'] = $total;
        $data['rows'] = $res;
        return json_encode($data);
    }

    /**
     *deleteInfo 删除资讯数据
     * @return 状态
     */
    public function deleteInfo(){
        $res = Db::table('ew_life')->delete($_POST['id']);
        if($res){
            Db::table('ew_life_message')->where('lm_life_id',$_POST['id'])->delete();
            return json_encode(['status'=>1,'msg'=>"删除成功！"]);
        }else{
            return json_encode(['status'=>0,'msg'=>"删除失败！"]);
        }
    }

    public function mww(){
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        if(!empty($_FILES['thumb']['tmp_name'])){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$_FILES['thumb']['name'])[1];
            $_FILES['thumb']['name'] = $rand . '.' .$exe;
            //=======================
            if(move_uploaded_file($_FILES['thumb']['tmp_name'],"{$dir}/mang/image/{$_FILES['thumb']['name']}")){
                $data['life_image'] = "{$url}/mang/image/{$_FILES['thumb']['name']}";
                return json_encode(['status'=>0,'url'=>$data['life_image']]);
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }
        if(!empty($_FILES['file']['tmp_name'])){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$_FILES['file']['name'])[1];
            $_FILES['file']['name'] = $rand . '.' .$exe;
            //=======================
            if(move_uploaded_file($_FILES['file']['tmp_name'],"{$dir}/mang/image/{$_FILES['file']['name']}")){
                $data['life_image'] = "{$url}/mang/image/{$_FILES['file']['name']}";
                return json_encode(['status'=>200,'url'=>$data['life_image']]);
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }
    }
    public function mwwdel(){
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $src = substr($_POST['src'],-24,24);
        if(is_file("{$dir}/mang/image/$src")){
            unlink("{$dir}/mang/image/$src");
        }
        return json_encode(['status'=>200,'msg'=>$src]);
    }
    public function mwwdel2(){
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $del = trim($_POST['src'],',');
        if($del){
            $del2 = explode(',',$del);
            foreach($del2 as $k=>$v){
                $src = substr($v,-24,24);
                if(is_file("{$dir}/mang/image/$src")){
                    unlink("{$dir}/mang/image/$src");
                }
            }
        }
        return json_encode(['status'=>200,'msg'=>$del]);
    }
    /**
     *editInfo 添加资讯-html
     * @return
     */
    public function addlife(){
        $type = Db::table('ew_life_type')->where('lt_status',1)->select();
        $this->assign ('type',$type);
        return $this->fetch("life/add");
    }
    /**
     *editInfo 添加资讯
     * @return
     */
    public function insertLife(){
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        $data = array();
//---------------缩略图单张上传---------------------
//        if(!empty($_FILES['thumb']['tmp_name'])){
//            //=======重命名=====
//            $rand = date('YmdHis').rand(100000,999999);
//            $exe = explode('.',$_FILES['thumb']['name'])[1];
//            $_FILES['thumb']['name'] = $rand . '.' .$exe;
//            //=======================
//            if(move_uploaded_file($_FILES['thumb']['tmp_name'],"{$dir}/mang/image/{$_FILES['thumb']['name']}")){
//                $data['life_image'] = "{$url}/mang/image/{$_FILES['thumb']['name']}";
//                if($_FILES['thumb']['size'] > 1024*500) {
//                    $this->image_png_size_add("$dir/mang/image/{$_FILES['thumb']['name']}", "$dir/mang/image/{$_FILES['thumb']['name']}");
//                }
//            }else{
//                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
//            }
//        }
//-------------------------end------------------
        $data['life_image'] = '';
        if(isset($_POST['thumb']) && $_POST['thumb']){
            $thumb = implode($_POST['thumb'],',');
            $data['life_image'] = trim($thumb,',');
        }
        $data['life_title'] = $_POST['title'];
        $data['life_type'] = $_POST['type'];
        $data['life_content'] = $_POST['con'];
        $data['life_time'] = date('Y-m-d H:i:s');
        $res = Db::table('ew_life')->insert($data);
        if($res){
            return json_encode(['status'=>1,'msg'=>"成功！"]);
        }else{
            return json_encode(['status'=>0,'msg'=>"失败！"]);
        }
    }
    /**
     *editInfo 修改资讯数据-html
     * @return 状态
     */
    public function editInfo(){
        $data = Db::table('ew_life')->where('life_id',$_POST['id'])->find();
        $img = array();
        if($data['life_image']){
            $img = explode(',',$data['life_image']);
        }
        $type = Db::table('ew_life_type')->where('lt_status',1)->select();
        $this->assign ('data',$data);
        $this->assign ('type',$type);
        $this->assign ('img',$img);
        return $this->fetch("life/edit");
    }
    /**
     *editInfo 修改资讯数据-html
     * @return 状态
     */
    public function seethreeInfo(){
        $data = Db::table('ew_life')->alias ('el')
            ->join('ew_u_user u','el.life_user_id=u.user_id','LEFT')
            ->join('ew_area a','el.life_sheng=a.district_id','LEFT')
            ->join('ew_area a2','el.life_shi=a2.district_id','LEFT')
            ->join('ew_area a3','el.life_qu=a3.district_id','LEFT')
            ->field('el.*,u.user_username,a.district sheng,a2.district shi,a3.district qu')
            ->where('life_id',$_POST['id'])
            ->find();
        $img = array();
        if($data['life_image']){
            $img = explode(',',$data['life_image']);
        }
        $this->assign ('data',$data);
        $this->assign ('img',$img);
        return $this->fetch("life/see_three");
    }

    /**
     *editInfo 修改资讯
     * @return 状态
     */
    public function updateLife(){
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        $data = array();
        //---------------缩略图单张上传---------------------
//        if(!empty($_FILES['thumb']['tmp_name'])){
//            //=======重命名=====
//            $rand = date('YmdHis').rand(100000,999999);
//            $exe = explode('.',$_FILES['thumb']['name'])[1];
//            $_FILES['thumb']['name'] = $rand . '.' .$exe;
//            //=======================
//            if(move_uploaded_file($_FILES['thumb']['tmp_name'],"{$dir}/mang/image/{$_FILES['thumb']['name']}")){
//                $data['life_image'] = "{$url}/mang/image/{$_FILES['thumb']['name']}";
//            }else{
//                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
//            }
//        }
        //-------------------------end------------------
        //=================多图且删除之前的，存又生成的=====================
        $del = $_POST['del'];
        if($del){
            $del2 = explode(',',$del);
            foreach($del2 as $k=>$v){
                $src = substr($v,-24,24);
                if(is_file("{$dir}/mang/image/$src")){
                    unlink("{$dir}/mang/image/$src");
                }
            }
        }
        if(isset($_POST['thumb']) && $_POST['thumb']){
            $thumb = implode($_POST['thumb'],',');
            $data['life_image'] = trim($thumb,',');
        }else{
            $data['life_image'] = '';
        }
        //======================================
        $data['life_title'] = $_POST['title'];
        $data['life_type'] = $_POST['type'];
        $data['life_content'] = $_POST['con'];
        $data['life_time'] = date('Y-m-d H:i:s');
        $res = Db::table('ew_life')->where('life_id',$_POST['fid'])
            ->update($data);
        if($res){
            return json_encode(['status'=>1,'msg'=>"成功！"]);
        }else{
            return json_encode(['status'=>0,'msg'=>"失败！"]);
        }
    }


    /**
     *getTypeData 获取资讯类型数据
     * @return json格式数组
     */
    public function getTypeData(){
        $where =array();
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        if(isset($_POST['keyword']) && $_POST['keyword']!=''){
            $keyword = $_POST['keyword'];
            $where['lt_name'] = array('like',"%$keyword%");
        }
        $res = Db::table('ew_life_type')
            ->where($where)
            ->limit($rows * ($page - 1), $rows)
            ->select();
        $total =Db::table('ew_life_type')
            ->where($where)
            ->count();
        $data['total'] = $total;
        $data['rows'] = $res;
        return json_encode($data);
    }

    /**
     * enableType 启用
     * @return 返回状态
     */
    public function enableType(){
        $data = $this->oneuser($_POST['cid'],1,"已启用！","启用失败！");
        return json_encode($data);
    }

    /**
     * disabledType 停用
     * @return 返回状态
     */
    public function disabledType(){
        $data = $this->oneuser($_POST['cid'],2,"已停用！","停用失败！");
        return json_encode($data);
    }

    /**
     * oneuser 停用或启用
     * @param、$uid用户id、$num状态值、$succemsg成功返回信息、$failedmsg失败返回信息
     * @return 返回状态
     */
    protected function oneuser($uid,$num,$succemsg,$failedmsg){
        if($uid!=''){
            $where['lt_id'] = $uid;
            $data['lt_status'] = $num;//停用|启用
            $res =  Db::table('ew_life_type')->where($where)->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = $succemsg;
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = $failedmsg;
            }
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "传递参数错误";
        }
        return $returnData;
    }

    /**
     * editInfoType 编辑类别
     * @return 返回状态
     */
    public function editInfoType(){
        $data = Db::table('ew_life_type')
            ->where('lt_id',$_POST['id'])
            ->find();
        $this->assign ('data',$data);
        return $this->fetch("life/edittype");
    }

    /**
     * update 编辑
     * @return 返回状态
     */
    public function update(){
        extract($_POST);
        if($lt_name ==""){
            return json_encode(['status'=>0,'msg'=>'类别名称不能为空！']);
        }else{
            $arr = Db::table('ew_life_type')->where('lt_id',$lt_id)->find();
            if($arr['lt_name']==$lt_name && $arr['lt_status']==$lt_status){
                return json_encode(['status'=>0,'msg'=>'请修改点内容！']);
            }else{
                $res = Db::table('ew_life_type')->where('lt_id',$lt_id)->update($_POST);
                if($res){
                    return json_encode(['status'=>1,'msg'=>"修改成功！"]);
                }else{
                    return json_encode(['status'=>0,"msg"=>"修改失败！"]);
                }
            }
        }
    }


    /**
     * addType 添加类别
     * @return 返回HTML
     */
    public function addType(){
        return $this->fetch('life/addtype');
    }

    /**
     * add 添加
     * @return 状态
     */
    public function add(){
        extract($_POST);
        if($lt_name ==""){
            return json_encode(['status'=>0,'msg'=>'类别名称不能为空！']);
        }else{
            $res = Db::table('ew_life_type')->insert($_POST);
            if($res){
                return json_encode(['status'=>1,'msg'=>"添加成功！"]);
            }else{
                return json_encode(['status'=>0,"msg"=>"添加失败！"]);
            }
        }
    }

    /**
     * deleteType 删除类别
     * @return 状态
     */
    public function deleteType(){
        $res = Db::table('ew_life_type')->delete($_POST['id']);
        if($res){
            return json_encode(['status'=>1,'msg'=>"删除成功！"]);
        }else{
            return json_encode(['status'=>0,'msg'=>"删除失败！"]);
        }
    }


    /**
     * 查看某用户的动态——html
     * @return string
     */
    public function myLifes() {
        $lifeid = $_POST['lifeid'];
        $this->assign ('lifeid',$lifeid);
        return $this->fetch("life/life_mes");
    }
    /**
     * 查看某用户的评论——数据
     * @return string
     */
    public function myLifeTable() {
        $lid = $_POST['lid'];
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        $res = Db::table("ew_life_message")->alias('cm')
            ->join('ew_u_user u','cm.lm_one_user_id=u.user_id','LEFT')
            ->join('ew_u_user u2','cm.lm_reply_user_id=u2.user_id','LEFT')
            ->field('cm.*,u.user_id one_id,u2.user_id reply_id,u.user_username one_name,u2.user_username reply_name')
            ->where('lm_life_id',$lid)
            ->limit($rows * ($page - 1), $rows)
            ->select();
        $total = Db::table("ew_life_message")->alias('cm')
            ->join('ew_u_user u','cm.lm_one_user_id=u.user_id','LEFT')
            ->join('ew_u_user u2','cm.lm_reply_user_id=u2.user_id','LEFT')
            ->field('u.user_id one_id')
            ->where('lm_life_id',$lid)
            ->count();
        $data['total'] = $total;
        $data['rows'] = $res;
        return json_encode($data);
    }
    /**
     * 删除某资讯里的评论的回复
     * @return string
     */
    public function dellifemes() {
        $lmid = $_POST['lmid'];
        // 启动事务
        Db::startTrans();
        try{
            $data = Db::table('ew_life_message')
                ->where('lm_id',$lmid)
                ->field('lm_life_id')
                ->find();
            $lid = $data['lm_life_id'];
            //删除掉这个动态的回复
            Db::table('ew_life_message')->where('lm_id',$lmid)->delete();
            Db::table('ew_life')
                ->where('life_id',$lid)
                ->setDec('life_message');
            // 提交事务
            Db::commit();
            return json_encode(['status'=>200,'msg'=>'成功']);
            //=====end===============
        } catch (\Exception $e) {
            return json_encode(['status'=>0,'msg'=>'失败']);
        }
    }

}